package com.chengyu.core.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chengyu.core.config.NewSecurityConfig;
import com.chengyu.core.constants.ICacheKeys;
import com.chengyu.core.entity.TblPointsImpower;
import com.chengyu.core.mapper.TblPointsImpowerMapper;
import com.chengyu.core.request.PointsImpowerReq;
import com.chengyu.core.service.ITblPointsImpowerService;
import com.chengyu.core.service.TblMemberService;
import com.chengyu.core.util.ConvertUtils;
import com.chengyu.core.util.NewRedisUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户授权减排场景 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2023-05-13
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class TblPointsImpowerServiceImpl extends ServiceImpl<TblPointsImpowerMapper, TblPointsImpower> implements ITblPointsImpowerService {

    private final NewSecurityConfig newSecurityConfig;
    private final NewRedisUtils newRedisUtils;
    private final TblMemberService tblMemberService;

    @Override
    public List<PointsImpowerReq> getAllMember() {
        return this.baseMapper.getAllMember();
    }



    @Override
    public boolean saveImpowerMember(List<PointsImpowerReq> list) throws Exception {
        log.info("saveImpowerMember---list"+ list.toString());



        List<TblPointsImpower> entityList = ConvertUtils.sourceToTarget(list, TblPointsImpower.class);
        List<TblPointsImpower> save = new ArrayList<>();
        for (TblPointsImpower impower : entityList) {
            int count = this.count(new LambdaUpdateWrapper<TblPointsImpower>()
                    .eq(TblPointsImpower::getPhone, impower.getPhone())
                    .eq(TblPointsImpower::getScenePort, impower.getScenePort())
                    .eq(TblPointsImpower::getStatus, 0));
            if (count == 0) {

                log.info("impower---"+ impower.toString());
                save.add(impower);
            }
        }
        if (!CollUtil.isEmpty(save)) {
            newRedisUtils.deleteByPattern(ICacheKeys.USER_IMPOWER_STATUS + list.get(0).getPhone());
            newRedisUtils.delete(ICacheKeys.IMPOWER_MEMBER_LIST__PHONE + list.get(0).getPhone());
//            tblMemberService.update(null, new LambdaUpdateWrapper<TblMemberEntity>()
//                    .set(TblMemberEntity::getUuid, list.get(0).getUnionId())
//                    .eq(TblMemberEntity::getPhone, NewEncryptUtils.encrypt(list.get(0).getPhone(), newSecurityConfig.getPhoneAesKey())));
            return saveBatch(entityList);
        }
        return true;
    }
}
